package com.wenqiner.requesttool.core.tool;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.wenqiner.requesttool.core.constants.FileConstant;
import com.wenqiner.requesttool.core.exception.CustomException;
import com.wenqiner.requesttool.domain.OriginRequestJsonData;
import com.wenqiner.requesttool.util.file.AbstractFileParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 占位符数据替换
 *
 * @author rhf
 * @date 2023-03-24
 **/
public class PlaceholderData {

    public static final Logger log = LoggerFactory.getLogger(PlaceholderData.class);

    private final AbstractFileParser fileParser;

    public PlaceholderData(AbstractFileParser fileParser) {
        this.fileParser = fileParser;
    }


    /**
     * 替换参数中占位符为文件中的值，返回请求体
     *
     * @param filePath  文件路径
     * @param headerMap 请求头
     * @param paramStr  请求json
     * @return java.util.List<java.lang.String>
     * @author rhf
     */
    public OriginRequestJsonData paramReplace(String filePath, Map<String, String> headerMap, String paramStr) {
        OriginRequestJsonData requestJsonData = new OriginRequestJsonData();
        if (CharSequenceUtil.isNotBlank(filePath)) {
            List<Map<String, String>> rowData = fileParser.parse(filePath);
            requestJsonData.setRowData(rowData);
        }
        requestJsonData.setHeaderMap(headerMap);
        requestJsonData.setBody(paramStr);
        return requestJsonData;
    }

    /**
     * 写到返回文件中
     *
     * @param filePath        结果文件路径
     * @param extractFieldStr 导出结果字段,  $.data.id;$.data.name;
     * @param resultFieldStr  对应导出结果字段,  id;name
     * @param resultMap       vale为json
     * @author rhf
     */
    public void writeToResult(String filePath, String extractFieldStr, String resultFieldStr, Map<String, String> resultMap) {
        if (CharSequenceUtil.isBlank(extractFieldStr)) {
            throw new CustomException("请指定导出字段");
        }
        String[] extractFields = extractFieldStr.split(FileConstant.RESULT_FIELD_SEPARATOR_REGEXP);
        if (ArrayUtil.isEmpty(extractFields)) {
            throw new CustomException("多个导出字段用,隔开");
        }
        log.info("导出文件，文件路径:[{}],文本行数:[{}],表头:[{}]", filePath, resultMap.size(), resultFieldStr);
        String[] fields = resultFieldStr.split(FileConstant.RESULT_FIELD_SEPARATOR_REGEXP);
        List<Map<String, String>> list = resultMap.values()
                .parallelStream()
                .map(json ->
                        getJsonValue(JSON.parseObject(json), extractFields, fields)
                ).collect(Collectors.toList());

        fileParser.writerToFile(filePath, list, ListUtil.of(fields));
    }

    /**
     * 获取单个值
     *
     * @param resultJson   单个result结果
     * @param extractField 替换的符号
     * @param fields       导出字段
     * @return java.util.Map<java.lang.String, java.lang.String>
     * @author rhf
     */
    private Map<String, String> getJsonValue(JSONObject resultJson, String[] extractField, String[] fields) {

        Map<String, String> rowMap = new LinkedHashMap<>();
        for (int f = 0; f < extractField.length; f++) {
            String[] split = extractField[f].split(FileConstant.JSON_SEPARATOR_REGEXP);
            JSONObject jsonObject = resultJson.clone();
            for (int i = 1; i < split.length; i++) {
                //最后一个取值为object
                if (i == split.length - 1) {
                    rowMap.put(fields[f], jsonObject.get(split[i]).toString());
                } else {
                    jsonObject = jsonObject.getJSONObject(split[i]);
                }
            }
        }
        return rowMap;
    }

}
